import { request } from './request'

// 活动相关接口类型定义
export interface Activity {
  id: number
  title: string
  description: string
  type: string
  status: 'draft' | 'published' | 'ongoing' | 'completed' | 'cancelled'
  startTime: string
  endTime?: string
  locationName: string
  locationAddress?: string
  latitude?: number
  longitude?: number
  coverImage?: string
  participantCount: number
  maxParticipants?: number
  budgetPerPerson?: number
  currency?: string
  registrationDeadline?: string
  visibility: 'public' | 'family' | 'friends' | 'private'
  requirements?: string
  notes?: string
  isParticipating: boolean
  canParticipate: boolean
  canEdit: boolean
  canDelete: boolean
  canShare: boolean
  canUpload: boolean
  allowComments: boolean
  autoApprove: boolean
  sendNotifications: boolean
  createTime: string
  updateTime: string
  creator?: {
    id: number
    name: string
    avatar?: string
  }
}

export interface ActivityForm {
  title: string
  description: string
  type: string
  status: string
  startTime: string
  endTime: string
  locationName: string
  locationAddress: string
  latitude: number | null
  longitude: number | null
  maxParticipants: number | null
  budgetPerPerson: number | null
  currency: string
  registrationDeadline: string
  visibility: string
  requirements: string
  notes: string
  coverImage: string
  allowComments: boolean
  autoApprove: boolean
  sendNotifications: boolean
}

export interface ActivityParticipant {
  id: number
  name: string
  avatar?: string
  relation?: string
  joinTime: string
  status?: 'confirmed' | 'pending' | 'declined'
  isCreator?: boolean
}

export interface ActivityPhoto {
  id: number
  thumbnailUrl: string
  originalUrl: string
  description?: string
  uploadTime: string
  uploaderName: string
  uploaderAvatar?: string
}

export interface ActivityComment {
  id: number
  content: string
  createTime: string
  likeCount: number
  isLiked: boolean
  user: {
    id: number
    name: string
    avatar?: string
  }
  replies?: ActivityComment[]
}

export interface ActivityStatistics {
  upcomingCount: number
  ongoingCount: number
  completedCount: number
  totalParticipants: number
}

export interface ActivitySearchParams {
  keyword?: string
  type?: string
  status?: string
  startDate?: string
  endDate?: string
  location?: string
  creatorId?: number
  participating?: boolean
  page?: number
  size?: number
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
}

export interface ActivityListResponse {
  list: Activity[]
  total: number
  page: number
  size: number
}

// 活动管理API
export const activityApi = {
  // 获取活动列表
  getActivityList: (params?: ActivitySearchParams) => 
    request<ActivityListResponse>({
      url: '/api/activity/list',
      method: 'GET',
      params
    }),

  // 获取活动详情
  getActivityDetail: (id: number) => 
    request<Activity>({
      url: `/api/activity/detail/${id}`,
      method: 'GET'
    }),

  // 创建活动
  createActivity: (data: ActivityForm) => 
    request<Activity>({
      url: '/api/activity/create',
      method: 'POST',
      data
    }),

  // 更新活动
  updateActivity: (id: number, data: Partial<ActivityForm>) => 
    request<Activity>({
      url: `/api/activity/update/${id}`,
      method: 'PUT',
      data
    }),

  // 删除活动
  deleteActivity: (id: number) => 
    request<void>({
      url: `/api/activity/delete/${id}`,
      method: 'DELETE'
    }),

  // 发布活动
  publishActivity: (id: number) => 
    request<Activity>({
      url: `/api/activity/publish/${id}`,
      method: 'POST'
    }),

  // 取消活动
  cancelActivity: (id: number) => 
    request<Activity>({
      url: `/api/activity/cancel/${id}`,
      method: 'POST'
    }),

  // 保存草稿
  saveDraft: (data: Partial<ActivityForm>) => 
    request<Activity>({
      url: '/api/activity/draft',
      method: 'POST',
      data
    }),

  // 上传活动封面
  uploadCover: (file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    return request<{url: string}>({
      url: '/api/activity/upload/cover',
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 获取活动统计
  getActivityStatistics: () => 
    request<ActivityStatistics>({
      url: '/api/activity/statistics',
      method: 'GET'
    }),

  // 搜索用户（用于邀请）
  searchUsers: (keyword: string) => 
    request<{
      id: number
      name: string
      avatar?: string
      relation: string
    }[]>({
      url: '/api/activity/search/users',
      method: 'GET',
      params: { keyword }
    }),

  // 邀请用户
  inviteUsers: (activityId: number, userIds: number[]) => 
    request<void>({
      url: `/api/activity/invite/${activityId}`,
      method: 'POST',
      data: { userIds }
    })
}

// 活动参与API
export const activityParticipationApi = {
  // 参加活动
  joinActivity: (activityId: number, message?: string) => 
    request<void>({
      url: `/api/activity/join/${activityId}`,
      method: 'POST',
      data: { message }
    }),

  // 取消参加
  leaveActivity: (activityId: number) => 
    request<void>({
      url: `/api/activity/leave/${activityId}`,
      method: 'POST'
    }),

  // 获取参与者列表
  getParticipants: (activityId: number) => 
    request<ActivityParticipant[]>({
      url: `/api/activity/participants/${activityId}`,
      method: 'GET'
    }),

  // 更新参与状态
  updateParticipationStatus: (activityId: number, userId: number, status: string) => 
    request<void>({
      url: `/api/activity/participation/status`,
      method: 'PUT',
      data: { activityId, userId, status }
    }),

  // 审核参与申请
  approveParticipation: (activityId: number, userId: number, approved: boolean) => 
    request<void>({
      url: `/api/activity/participation/approve`,
      method: 'POST',
      data: { activityId, userId, approved }
    }),

  // 移除参与者
  removeParticipant: (activityId: number, userId: number) => 
    request<void>({
      url: `/api/activity/participation/remove`,
      method: 'DELETE',
      data: { activityId, userId }
    })
}

// 活动相册API
export const activityPhotoApi = {
  // 获取活动相册
  getActivityPhotos: (activityId: number, page?: number, size?: number) => 
    request<{
      list: ActivityPhoto[]
      total: number
    }>({
      url: `/api/activity/photos/${activityId}`,
      method: 'GET',
      params: { page, size }
    }),

  // 上传活动照片
  uploadPhotos: (activityId: number, files: File[], descriptions?: string[]) => {
    const formData = new FormData()
    files.forEach((file, index) => {
      formData.append('files', file)
      if (descriptions && descriptions[index]) {
        formData.append('descriptions', descriptions[index])
      }
    })
    return request<ActivityPhoto[]>({
      url: `/api/activity/photos/upload/${activityId}`,
      method: 'POST',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 删除照片
  deletePhoto: (photoId: number) => 
    request<void>({
      url: `/api/activity/photos/delete/${photoId}`,
      method: 'DELETE'
    }),

  // 更新照片信息
  updatePhoto: (photoId: number, description: string) => 
    request<ActivityPhoto>({
      url: `/api/activity/photos/update/${photoId}`,
      method: 'PUT',
      data: { description }
    })
}

// 活动评论API
export const activityCommentApi = {
  // 获取活动评论
  getActivityComments: (activityId: number, page?: number, size?: number) => 
    request<{
      list: ActivityComment[]
      total: number
    }>({
      url: `/api/activity/comments/${activityId}`,
      method: 'GET',
      params: { page, size }
    }),

  // 发表评论
  createComment: (activityId: number, content: string, parentId?: number) => 
    request<ActivityComment>({
      url: `/api/activity/comments/create`,
      method: 'POST',
      data: { activityId, content, parentId }
    }),

  // 删除评论
  deleteComment: (commentId: number) => 
    request<void>({
      url: `/api/activity/comments/delete/${commentId}`,
      method: 'DELETE'
    }),

  // 点赞评论
  likeComment: (commentId: number) => 
    request<void>({
      url: `/api/activity/comments/like/${commentId}`,
      method: 'POST'
    }),

  // 取消点赞评论
  unlikeComment: (commentId: number) => 
    request<void>({
      url: `/api/activity/comments/unlike/${commentId}`,
      method: 'POST'
    }),

  // 举报评论
  reportComment: (commentId: number, reason: string) => 
    request<void>({
      url: `/api/activity/comments/report`,
      method: 'POST',
      data: { commentId, reason }
    })
}

// 活动分享API
export const activityShareApi = {
  // 生成分享链接
  createShareLink: (activityId: number, options?: {
    password?: string
    expireTime?: string
    allowDownload?: boolean
    watermark?: boolean
  }) => 
    request<{
      shareId: string
      shareUrl: string
      qrCode: string
    }>({
      url: `/api/activity/share/create/${activityId}`,
      method: 'POST',
      data: options
    }),

  // 获取分享信息
  getShareInfo: (shareId: string, password?: string) => 
    request<{
      activity: Activity
      photos: ActivityPhoto[]
      allowDownload: boolean
    }>({
      url: `/api/activity/share/info/${shareId}`,
      method: 'GET',
      params: { password }
    }),

  // 获取分享统计
  getShareStatistics: (activityId: number) => 
    request<{
      shareCount: number
      viewCount: number
      downloadCount: number
      recentVisitors: Array<{
        ip: string
        location: string
        time: string
        userAgent: string
      }>
    }>({
      url: `/api/activity/share/statistics/${activityId}`,
      method: 'GET'
    }),

  // 删除分享链接
  deleteShareLink: (shareId: string) => 
    request<void>({
      url: `/api/activity/share/delete/${shareId}`,
      method: 'DELETE'
    })
}

// 活动推荐API
export const activityRecommendApi = {
  // 获取推荐活动
  getRecommendedActivities: (page?: number, size?: number) => 
    request<ActivityListResponse>({
      url: '/api/activity/recommend',
      method: 'GET',
      params: { page, size }
    }),

  // 获取相似活动
  getSimilarActivities: (activityId: number, limit?: number) => 
    request<Activity[]>({
      url: `/api/activity/similar/${activityId}`,
      method: 'GET',
      params: { limit }
    }),

  // 获取热门活动
  getPopularActivities: (timeRange?: 'day' | 'week' | 'month', limit?: number) => 
    request<Activity[]>({
      url: '/api/activity/popular',
      method: 'GET',
      params: { timeRange, limit }
    }),

  // 获取附近活动
  getNearbyActivities: (latitude: number, longitude: number, radius?: number, limit?: number) => 
    request<Activity[]>({
      url: '/api/activity/nearby',
      method: 'GET',
      params: { latitude, longitude, radius, limit }
    }),

  // 记录用户行为（用于推荐优化）
  recordUserAction: (activityId: number, action: 'view' | 'like' | 'share' | 'join') => 
    request<void>({
      url: '/api/activity/action',
      method: 'POST',
      data: { activityId, action }
    })
}

// 位置服务API
export const locationApi = {
  // 获取当前位置
  getCurrentLocation: () => 
    new Promise<{latitude: number, longitude: number}>((resolve, reject) => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          position => resolve({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
          }),
          error => reject(error),
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 60000
          }
        )
      } else {
        reject(new Error('Geolocation is not supported'))
      }
    }),

  // 地址解析
  geocodeAddress: (address: string) => 
    request<{
      latitude: number
      longitude: number
      formattedAddress: string
    }>({
      url: '/api/location/geocode',
      method: 'GET',
      params: { address }
    }),

  // 反向地址解析
  reverseGeocode: (latitude: number, longitude: number) => 
    request<{
      address: string
      components: {
        country: string
        province: string
        city: string
        district: string
        street: string
      }
    }>({
      url: '/api/location/reverse-geocode',
      method: 'GET',
      params: { latitude, longitude }
    }),

  // 搜索地点
  searchPlaces: (keyword: string, location?: {latitude: number, longitude: number}) => 
    request<Array<{
      id: string
      name: string
      address: string
      latitude: number
      longitude: number
      category: string
      distance?: number
    }>>({
      url: '/api/location/search',
      method: 'GET',
      params: { 
        keyword, 
        ...(location && { lat: location.latitude, lng: location.longitude })
      }
    }),

  // 获取热门地点
  getPopularPlaces: (type?: string, limit?: number) => 
    request<Array<{
      id: string
      name: string
      address: string
      latitude: number
      longitude: number
      category: string
      usageCount: number
    }>>({
      url: '/api/location/popular',
      method: 'GET',
      params: { type, limit }
    })
}

// 统一导出
export default {
  activityApi,
  activityParticipationApi,
  activityPhotoApi,
  activityCommentApi,
  activityShareApi,
  activityRecommendApi,
  locationApi
}